﻿using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FFSupplier.ServiceCore.Model
{
    public class PageEntityModel
    {
        public long VersionNumber { get; set; }
        public string EntityName { get; set; }
        public object this[int index] { get { return Attributes.ToList()[index]; } }
        public object this[string name]
        {
            get { return Attributes[name]; }
            set
            {
                if (Attributes.ContainsKey(name))
                {
                    Attributes[name] = value;
                }
                else
                {
                    Attributes.Add(name, value);
                }
            }
        }
        public Dictionary<string, object> Attributes { get; set; }
        public PageEntityModel()
        {
            Attributes = new Dictionary<string, object>();
        }
        public bool ContainsKey(string name)
        {
            return Attributes.ContainsKey(name);
        }
        public Entity ToEntity(string entityName)
        {
            Entity result = new Entity(entityName);
            result.Attributes = new AttributeCollection();
            result.Attributes.AddRange(this.Attributes);
            return result;
        }

        public T ToEntity<T>(string entityName) where T : Entity
        {
            T result = this.ToEntity(entityName).ToEntity<T>();
            return result;
        }

        public void Clear()
        {
            Attributes.Clear();
        }

        public void AddRange(IEnumerable<KeyValuePair<string, object>> items)
        {
            foreach (var item in items)
            {
                Attributes.Add(item.Key, item.Value);
            }
        }
    }
}
